package dubbo.learn.core.config.parser;

import dubbo.learn.core.component.reference.RemoteServiceReferenceFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class ServiceReferenceBeanDefinitionParser implements BeanDefinitionParser {
    private static final String INTERFACE = "interface";

    private static final String REMOTE_INTERFACE_NAME = "remoteInterfaceName";

    private static final String ID = "id";

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext) {
        /**
         * 解析xml配置,获取服务名称
         */
        String remoteReferenceName = element.getAttribute(INTERFACE);

        String id = element.getAttribute(ID);

        /**
         * 生成bean definition
         */
        RootBeanDefinition rootBeanDefinition = createBeanDefinition(remoteReferenceName);
        parserContext.getRegistry().registerBeanDefinition(id, rootBeanDefinition);

        return null;
    }

    protected RootBeanDefinition createBeanDefinition(String remoteInterfaceName) {
        RootBeanDefinition beanDefinition = new RootBeanDefinition(RemoteServiceReferenceFactory.class);
        beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
        beanDefinition.setSynthetic(true);
        beanDefinition.getPropertyValues().add(REMOTE_INTERFACE_NAME, remoteInterfaceName);
        return beanDefinition;
    }
}
